import json
import re
from time import sleep
import requests
import base64
from PIL import Image
from io import BytesIO

class reqCode:
    def reqImg(self):
        url = "https://gwzaapp.com/api/captchaImage"
        payload = {}
        headers = {}
        response = requests.request("GET", url, headers=headers, data=payload, verify=False)
        img = response.json()["img"]
        uuid = response.json()["uuid"]
        # print(img)
        # 输入base64编码的图像数据
        base64_data = "data:image/gif;base64," + img
        # 解码base64数据
        image_data = base64.b64decode(base64_data.split(",")[1])
        #print(image_data)
        # 将二进制数据读取为图像
        image = Image.open(BytesIO(image_data))
        # 保存图像到本地文件
        image.save("test.png")
        return base64_data,uuid

    def reqImgCode(self,base64_data):
        url = "http://127.0.0.1:8889/infer64"
        headers = {
            'Access-Control-Allow-Origin': '*',
            'check': '5',
        }
        # 读取图片文件并转换成二进制形式
        # with open('test.png', 'rb') as file:
        #     image_binary = file.read()

        payload = json.dumps({'img': base64_data})

        # FormData参数设置  将base64解密后的数据传入
        # files = [
        #     ('image', ('test.png', base64_data, 'image/png'))
        # ]
        res = requests.post(url, headers=headers, data=payload)
        #print(res.json())
        json_data = res.json()['out_str']
        print(json_data)
        # 使用正则表达式匹配"ask"的值
        matches = re.findall(r'"ask"\s*:\s*(\d+)', json_data)
        # 提取匹配结果
        if matches:
            ask_value = int(matches[0])
            print("Ask的值为:", ask_value)
        else:
            print("未找到Ask的值")

        return ask_value

    def loginSystem(self,user,psd,code,uuid):
        url = "https://gwzaapp.com/api/login"
        payload = json.dumps({
            "username": user,
            "password": psd,
            "code": code,
            "uuid": uuid
        })
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        token = response.json()['token']
        memberId = response.json()['memberId']

        return token,memberId

if __name__ == '__main__':
    user = "admin"
    psd = "jZh8/RKWxy3LqV2m3CGK1f1RIrPH7s9Mh4EhtuFkH5Ax4TDSC8ybXDynyKnT1upgZkLZVXR7B7E4thkmAg/4OvG2ENYPQJ49qNR92tki430z9O2Dmw2BKJ2cpRhmq4qOXROud5hE4oSdPZ67cyfQ+WanIhRemrvQNhxTpzdyRRMDcobtoye/h4YTDH9TZ3RAcdu3JEtOoDce12AAvz8Mm7SFGNv2niHuYDSNRF4F36zV3rMe3a7vLGdPaEJJ4JWiujJCczSulVuIeq/drpDPBJgBeTILAXrId/DkSQ47oQcREQVPIJPnHAwoarac8QCS2A6iOvJEURKWO5kGZxodKQ=="
    rc = reqCode()
    base64_data, uuid = rc.reqImg()
    print(base64_data)
    print(uuid)
    code = str(rc.reqImgCode(base64_data))
    token, memberId = rc.loginSystem(user,psd,code,uuid)
    print(token)
    print(memberId)











